@page "/fss/task_group/list"
@page "/fss/task_group/list/{pageIndex:int}"
@using FOPS.Abstract.Fss.Server
@using FOPS.Abstract.Fss.Entity
@using FS.Extends
@using System.Timers;
@inject IIocManager _iocManager;
@inject NavigationManager nav;
@inject IJSRuntime js;
@inject Blazored.LocalStorage.ILocalStorageService storage;
@implements IDisposable;

<div class="layui-card">
    <div class="layui-card-header" id="anchor-play-header">
        任务组
        <select style="display:inline;width: 200px;" @onchange="EnableChange">
            <option value="-1">全部</option>
            <option value="1">开启</option>
            <option value="0">停止</option>
        </select>

        <select style="display:inline;width: 200px;" @onchange="JobChange">
            <option value="">全部</option>
            @foreach (var jobName in lstJobName)
            {
                <option value="@jobName">@jobName</option>
            }
        </select>
        <div class="layui-right">
            <button class="layui-btn layui-btn-right" @onclick=RefreshCache><i class="am-icon-plus"></i> 刷新缓存</button>
            <button class="layui-btn layui-btn-right" @onclick=GotoAdd><i class="am-icon-plus"></i> 添加任务组</button>
        </div>
    </div>
    <div class="layui-card-body">
        <div class="layui-form layui-border-box layui-table-view" lay-filter="LAY-table-1" style=" ">
            <div class="layui-table-box">
                <div class="layui-table-header">
                    <table cellspacing="0" cellpadding="0" border="0" class="layui-table" lay-skin="auto" lay-size="sm">
                        <thead>
                        <tr>
                            <th data-field="ID">
                                <div class="layui-table-cell laytable-cell-14-0-0">
                                    <span>组ID</span>
                                </div>
                            </th>
                            <th data-field="Title">
                                <div class="layui-table-cell laytable-cell-14-0-2">
                                    <span>任务标题</span>
                                </div>
                            </th>
                            <th data-field="Games">
                                <div class="layui-table-cell laytable-cell-14-0-3">
                                    <span>下次执行</span>
                                </div>
                            </th>
                            <th data-field="Games">
                                <div class="layui-table-cell laytable-cell-14-0-4">
                                    <span>计划设置</span>
                                </div>
                            </th>
                            <th data-field="Games">
                                <div class="layui-table-cell laytable-cell-14-0-5">
                                    <span>活动时间</span>
                                </div>
                            </th>
                            <th data-field="Games">
                                <div class="layui-table-cell laytable-cell-14-0-6">
                                    <span>上次完成</span>
                                </div>
                            </th>
                            <th data-field="Games">
                                <div class="layui-table-cell laytable-cell-14-0-7">
                                    <span>平均耗时</span>
                                </div>
                            </th>
                            <th data-field="Games">
                                <div class="layui-table-cell laytable-cell-14-0-8">
                                    <span>运行次数</span>
                                </div>
                            </th>
                            <th data-field="Type">
                                <div class="layui-table-cell laytable-cell-14-0-9">
                                    <span>操作</span>
                                </div>
                            </th>
                        </tr>
                        </thead>
                    </table>
                </div>
                <div class="layui-table-body layui-table-main">
                    <table cellspacing="0" cellpadding="0" border="0" class="layui-table" lay-skin="auto" lay-size="sm">
                        <tbody>
                        @for (var index = 0; index < _lst.Count; index++)
                        {
                            var info = _lst[index];
                            <tr data-index="@index">
                                <td>
                                    <div class="laytable-cell-14-0-0">【@(info.IsEnable ? "开启" : "停止")】 @info.Id</div>
                                </td>
                                <td data-field="Title">
                                    <div class="laytable-cell-14-0-2">
                                        <a href="/fss/tasks/list/@info.Id">【@info.JobName】@info.Caption</a>
                                    </div>
                                </td>
                                <td data-field="Items">
                                    <div class="layui-table-cell laytable-cell-14-0-3">@info.NextAt.ToString("yyyy-MM-dd HH:mm:ss")</div>
                                </td>
                                <td data-field="Games">
                                    <div class="layui-table-cell laytable-cell-14-0-4">@GetTimeSetting(info)</div>
                                </td>
                                <td data-field="Games">
                                    <div class="layui-table-cell laytable-cell-14-0-5">@info.ActivateAt.ToString("yyyy-MM-dd HH:mm:ss")</div>
                                </td>
                                <td data-field="Games">
                                    <div class="layui-table-cell laytable-cell-14-0-6">@info.LastRunAt.ToString("yyyy-MM-dd HH:mm:ss")</div>
                                </td>
                                <td data-field="Games">
                                    <div class="layui-table-cell laytable-cell-14-0-7">@info.RunSpeedAvg</div>
                                </td>
                                <td data-field="Games">
                                    <div class="layui-table-cell laytable-cell-14-0-8">@info.RunCount</div>
                                </td>
                                <td data-field="Title">
                                    <div class="layui-table-cell laytable-cell-14-0-9">
                                        <button class="layui-btn layui-btn-sm" @onclick="() => GotoUpdate(info.Id)">编辑</button>
                                        <button class="layui-btn layui-btn-sm layui-btn-normal" @onclick="() => Copy(info)">复制</button>
                                        <button class="layui-btn layui-btn-sm @(info.IsEnable ? "layui-btn-primary" : "layui-btn-danger")" @onclick="() => SetEnable(info)">@(info.IsEnable ? "停止" : "开启")</button>
                                    </div>
                                </td>
                            </tr>
                        }
                        </tbody>
                    </table>
                </div>
            </div>
            <PageSplit PageIndex="@PageIndex" PageSize="@_pageSize" TotalCount="@_totalCount" PageUrl="/fss/task_group/list/{index}"></PageSplit>
        </div>
    </div>
</div>
<style>
    .laytable-cell-14-0-0{ width: 80px; }
    .laytable-cell-14-0-1{ width: 100px; }
    .laytable-cell-14-0-2{ width: 300px; }
    .laytable-cell-14-0-3{ width: 150px; }
    .laytable-cell-14-0-4{ width: 120px; }
    .laytable-cell-14-0-5{ width: 150px; }
    .laytable-cell-14-0-6{ width: 150px; }
    .laytable-cell-14-0-7{ width: 80px; }
    .laytable-cell-14-0-8{ width: 80px; }
    .laytable-cell-14-0-9{ width: 200px; }
</style>

@code{

    private int _lastIndex;
    [Parameter]
    public int PageIndex { get; set; }
    private int _totalCount;
    private int _pageSize = 20;

    private List<TaskGroupVO> _lst = new();
    private bool _isFirst;
    private Timer _timer;
    private int enable = -1;
    private List<string> lstJobName = new();
    private string jobName;

    protected override async Task OnParametersSetAsync()
    {
        if (_isFirst && _lastIndex == PageIndex) return;
        _isFirst = true;

        if (PageIndex < 1) PageIndex = 1;
        _lastIndex = PageIndex;
        await GetList();
    }

    protected override Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            _timer = new Timer(5000);
            _timer.Elapsed += async (_, _) =>
            {
                try
                {
                    await GetList();
    // 刷新页面
                    await InvokeAsync(StateHasChanged);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            };
            _timer.Enabled = true;
        }
        return Task.FromResult(0);
    }

    private async Task GetList()
    {
        _lst = await _iocManager.Resolve<IFssApi>().GetTaskGroupListAsync(storage) ?? new();
        _lst = _lst.OrderBy(o => o.JobName).ThenByDescending(o => o.Id).ToList();

    // 取出JobName
        lstJobName = _lst.Select(o => o.JobName).Distinct().ToList();
    // 筛选JobName
        if (!string.IsNullOrWhiteSpace(jobName)) _lst = _lst.FindAll(o => o.JobName == jobName);

    // 筛选状态
        if (enable > -1) _lst = _lst.FindAll(o => o.IsEnable == enable.ConvertType(false));

        _totalCount = _lst.Count;
        _lst = _lst.ToList(_pageSize, PageIndex);
    }

    private string GetTimeSetting(TaskGroupVO group)
    {
        return !string.IsNullOrWhiteSpace(group.Cron) ? group.Cron : $"{group.IntervalMs} ms";
    }

    private async Task RefreshCache()
    {
        await _iocManager.Resolve<IFssApi>().SyncCacheToDbAsync(storage);
        await GetList();

        await js.InvokeVoidAsync("layer.msg", "刷新成功", new
        {
            icon = 1
        });
        nav.NavigateTo("/fss/task_group/list");
    }

    private void GotoAdd()
    {
        nav.NavigateTo("/fss/task_group/add");
    }

    private void GotoUpdate(int id)
    {
        nav.NavigateTo($"/fss/task_group/update/{id}");
    }

    /// 复制项目
    private async Task Copy(TaskGroupVO info)
    {
        var id = await _iocManager.Resolve<IFssApi>().CopyTaskGroupAsync(storage,info.Id);
        nav.NavigateTo($"/fss/task_group/update/{id.Data}");
    }

    // 筛选组状态
    private Task EnableChange(ChangeEventArgs args)
    {
        enable = args.Value.ConvertType(0);
        return GetList();
    }

    private Task JobChange(ChangeEventArgs args)
    {
        jobName = args.Value.ToString();
        return GetList();
    }

    private async Task SetEnable(TaskGroupVO info)
    {
        info.IsEnable = !info.IsEnable;
        await _iocManager.Resolve<IFssApi>().SaveTaskGroupAsync(storage,info);
        await GetList();
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }
}